<template>
  <div class="wechat">
    <!-- 卡片视图区域 -->
    <div class="wechat_card">
      <!--搜索框与按钮-->
      <el-row :gutter="20"
              class="wechat_card_head">
        <!-- <el-col :span="8">

          <el-input placeholder="输入关键字查询"
                    v-model="queryInfo.query"
                    clearable
                    @clear="getTableList">
            <el-button slot="append"
                       icon="el-icon-search"
                       @click="getTableList"></el-button>
          </el-input>
        </el-col> -->
        <!-- <el-col :span="3">
          <el-button type="primary"
                     @click="showAddDialog(-1)"
                     icon="el-icon-circle-plus-outline"
                     style="width:100%">添加一级菜单</el-button>
        </el-col> -->
        <!-- <el-col :span="3">
          <el-button type="danger"
                     @click="deleteRecordByIds"
                     icon="el-icon-remove-outline"
                     style="width:100%">批量删除</el-button>
        </el-col> -->
        <!-- <el-col :span="3">
          <el-button type="success"
                     @click="deleteRecordByIds"
                     icon="el-icon-download"
                     style="width:100%">导出EXCEL</el-button>
        </el-col> -->
      </el-row>

      <!-- 表格区域 -->
      <el-table :data="tableFilterData.dataList"
                style="width: 100%"
                height="85%"
                stripe
                size="small"
                @selection-change="handleSelectionChange"
                row-key="id"
                default-expand-all:false
                :tree-props="{children: 'childrens'||'buttons', hasChildren: 'hasChildren'}">
        <el-table-column prop="name"
                         label="菜单名称"
                         width="400">
        </el-table-column>
        <el-table-column prop="url"
                         label="路径"
                         width="313">
        </el-table-column>
        <el-table-column prop="rank"
                         label="排序"
                         width="228">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 添加子菜单按钮 -->
            <!-- <el-tooltip v-if="scope.row.id < 1000 "
                        effect="dark"
                        content="添加子菜单"
                        placement="top"
                        :enterable="false">
              <el-button type="warning"
                         icon="el-icon-plus"
                         size="mini"
                         @click="showAddDialog(scope.row.id)"></el-button>
            </el-tooltip> -->
            <!-- 编辑按钮 -->
            <el-button v-has="'1113'"
                       type="primary"
                       icon="el-icon-edit"
                       size="mini"
                       @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <!-- <el-button type="danger"
                       icon="el-icon-delete"
                       size="mini"
                       @click="removeUserById(scope.row.id)"></el-button> -->

          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <!-- <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="this.queryInfo.pageNum"
                     :page-sizes="[3, 7, 15, 20, 30]"
                     :page-size="this.queryInfo.pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total"></el-pagination> -->

      <!-- 添加子分类的对话框 -->
      <el-dialog title="添加菜单分类"
                 :visible.sync="addDialogVisible"
                 @close="addDialogClosed"
                 width="50%">
        <!-- 内容主体区 -->
        <el-form :model="addForm"
                 :rules="addFormRules"
                 ref="addFormRef"
                 label-width="100px">
          <el-form-item label="菜单名称"
                        prop="name">
            <el-input v-model="addForm.name" />
          </el-form-item>
          <div :v-if="this.parentIdAble">
            <el-form-item label="父级菜单"
                          prop="parentId"
                          v-if="this.parentIdAble">
              <el-input v-model="addForm.parentId" />
            </el-form-item>
          </div>
          <div :v-if="this.menuIdAble">
            <el-form-item label="所属三级菜单"
                          prop="menuId"
                          v-if="this.menuIdAble">
              <el-input v-model="addForm.menuId" />
            </el-form-item>
          </div>
          <div :v-if="this.urlAble">
            <el-form-item label="地址"
                          prop="url"
                          v-if="this.urlAble">
              <el-input v-model="addForm.url" />
            </el-form-item>
          </div>
          <el-form-item label="排序"
                        prop="rank">
            <el-input-number v-model="addForm.rank"
                             @change="handleChange"
                             :min="1"
                             :max="10"
                             label="请输入排序等级"></el-input-number>
          </el-form-item>

        </el-form>
        <!-- 底部区域 -->
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="addMenu()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改菜单分类对话框 -->
      <el-dialog title="编辑菜单分类"
                 :visible.sync="editDialogVisible"
                 width="50%"
                 @close="editDialogClosed">
        <el-form :model="editForm"
                 :rules="editFormRules"
                 ref="editFormRef"
                 label-width="70px">
          <el-form-item label="菜单名称">
            <el-input v-model="editForm.name"
                      prop="name"></el-input>
          </el-form-item>
          <el-form-item v-if="editForm.parentId!=null"
                        label="父级"
                        prop="parentId">
            <el-input v-model="editForm.parentId"></el-input>
          </el-form-item>
          <el-form-item v-if="editForm.menuId!=null"
                        label="父级菜单"
                        prop="menuId">
            <el-input v-model="editForm.menuId"></el-input>
          </el-form-item>
          <el-form-item v-if="editForm.url!=null"
                        label="地址"
                        prop="url">
            <el-input v-model="editForm.url" />
          </el-form-item>
          <el-form-item label="排序"
                        prop="rank">
            <el-input-number v-model="editForm.rank"
                             @change="handleChange"
                             :min="1"
                             :max="10"
                             label="请输入排序等级"></el-input-number>
          </el-form-item>

        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="editRecordInfo">确 定</el-button>
        </span>
      </el-dialog>

    </div>
  </div>
</template>
<script>
import {
  getList,
  add,
  deleteSelected,
  deleteCurrent,
  getEditInfo,
  edit,
  getDetail,
  modifySwitch,
} from "@/api/logistics/logisticsGreen.js";
export default {
  data () {
    return {
      //当前选中行的id
      nowId: '',
      // 根据当前记录是否为xx级菜单选择当前输入框是否可以显示
      nameAble: true,
      parentIdAble: true,
      menuIdAble: true,
      urlAble: true,
      rankAble: true,
      // 表格列筛选数据
      tableFilterData: {
        dataList: [],
        dataNow: [
          { label: "	序号	", attr: "id", checked: false },
          { label: "	类型名称	", attr: "name", checked: true },
          { label: "	二级类型名称	", attr: "childrenName", checked: true },
          { label: "	小区id（公共为0）	", attr: "communityId", checked: false },
          { label: "	添加人	", attr: "addUserId", checked: false },
          { label: "	添加人姓名	", attr: "addUserName", checked: true },
          { label: "	添加时间	", attr: "addTime", checked: true },
          { label: "	备注	", attr: "memo", checked: false },

        ],

        checkLabels: [], // 筛选列显示多选框数据
        checkBoxList: [], // 筛选列数据
        indexTwo: 0,
      },
      // 记录列表分页区的参数
      queryInfo: {
        //搜索条件
        query: "",
        // 当前页码
        pageNum: 1,
        //每页显示条数
        pageSize: 7,
      },
      total: 0,


      // 控制添加记录对话框的显示与隐藏
      addDialogVisible: false,
      // 添加记录的表单数据
      addForm: {
        id: "",
        name: "",
        parentId: "",
        menuId: "",
        url: "",
        rank: 1,

      },
      // 添加表单校验规则
      addFormRules: {},


      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的用户信息
      editForm: {},
      // 编辑表单校验规则
      editFormRules: {},


      // 控制详细信息抽屉的显示与隐藏
      drawerVisible: false,
      // 详细信息的表单数据
      detailForm: {},
      // 被选中的记录id
      selectedList: [],
      selectedStr: {
        ids: "",
      },
      deleteNow: {
        ids: "",
      },
    }
  },
  created () {
    this.getTableList();
  },
  methods: {
    // 获取列表信息
    async getTableList () {
      // if (this.queryInfo.query !== '')
      //   this.queryInfo.condition = `name like "%${this.queryInfo.query}%"`
      const { data: res } = await this.$http.get("SystemmenuAction/getSystemMenus")
      console.log(res)
      if (!res.success) return this.$message.error('获取表格数据失败')
      // this.$message.success('获取列表数据成功')
      this.tableFilterData.dataList = res.rows
      this.total = res.total

    },
    // 监听排序增减组件
    handleChange () {

    },
    // 监听多选框选中的所有记录
    handleSelectionChange (val) {
      this.selectedList = val;
    },
    // 监听pageSize改变的事件
    handleSizeChange (newSize) {
      console.log(newSize)
      this.queryInfo.pageSize = newSize
      this.getTableList()
    },
    // 监听页码值改变的事件
    handleCurrentChange (newPage) {
      console.log(newPage)
      this.queryInfo.pageNum = newPage
      this.getTableList()
    },
    // 监听添加对话框的关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 监听修改对话框的关闭
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 表头列筛选功能
    filterFunHandle (type, currentItem, index) {
      if (type === 'filter') { // 筛选列
        if (event.target.checked === false) {
          this.tableFilterData.dataNow.forEach((item, index, arr) => {
            if (item.attr === currentItem) {
              return item.checked = false
            }
          })
        } else {
          this.tableFilterData.dataNow.forEach((item, index, arr) => {
            if (item.attr === currentItem) {
              return item.checked = true
            }
          })
        }
      } else if (type === 'allchecked') { // 全选
        if (this.tableFilterData.checkLabels.length === 0) {
          this.tableFilterData.dataNow.forEach((result) => {
            this.tableFilterData.checkLabels.push(result.attr)
          })
          this.tableFilterData.checkBoxList = this.tableFilterData.checkLabels // 复选框置为复选所有值，全部选择    
        } else {
          this.tableFilterData.checkBoxList = this.tableFilterData.checkLabels // 复选框置为复选所有值，全部选择
        }
        this.tableFilterData.dataNow.forEach((item, index, arr) => {
          item.checked = true
        })
      } else if (type === 'cancel') { // 取消全选
        this.tableFilterData.checkBoxList = [] // 复选框置为空，全部不选择
        this.tableFilterData.dataNow.forEach((item, index, arr) => {
          item.checked = false
        })
      }
    },






    // 添加记录
    addRecord () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 可以发起添加记录的网络请求
        await add(
          this.addForm.name,
          this.addForm.password,
          this.addForm.phone,
          this.addForm.roleId
        ).then((res) => {
          if (res.meta.status !== 201) {
            this.$message.error('添加记录失败！')
          }
          this.$message.success('添加记录成功！')
          // 隐藏添加记录的对话框
          this.addDialogVisible = false
          // 重新获取记录列表数据
          this.getTableList()
        })
      })
    },
    // 删除（批量）
    async deleteRecordByIds () {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户确认删除，返回值为字符串confirm
      // 如果用户取消删除，返回值未字符串cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      await deleteSelected(this.selectedList).then((res) => {
        if (res.meta.status !== 200) {
          return this.$message.error('删除记录失败！')
        }
        this.$message.success('删除记录成功！')
        this.getTableList()
      })

    },
    //添加子菜单
    showAddDialog (id) {
      this.nowId = id
      //将所有输入框都重置为可显示
      this.nameAble = true
      this.parentIdAble = true
      this.menuIdAble = true
      this.urlAble = true
      this.rankAble = true
      this.addForm.parentId = id
      this.addForm.menuId = id

      //如果是添加一级菜单，只保留名称输入框
      if (id < 0) {
        this.menuIdAble = false
        this.parentIdAble = false
        this.urlAble = false
      } else if (id < 100) { //如果当前是一级或二级菜单，即添加的是二或三级菜单，那么menuId这个属性是不能输入的
        this.menuIdAble = false
      } else { //当前是三级菜单，添加的是按钮，那么parentId和url是不能显示的
        this.parentIdAble = false
        this.urlAble = false
      }
      this.addDialogVisible = true

    },
    //确认添加子菜单
    addMenu () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        //对rank进行处理，转化为浮点型
        this.addForm.rank = this.addForm.rank / 10
        if (this.nowId < 0) {
          const { data: res } = await this.$http.post("SystemmenuAction/addObject", this.addForm)
          if (!res.success) return this.$message.error('添加失败')
          this.$message.success('添加记录成功！')
          this.addDialogVisible = false
          this.getTableList()
        } else if (this.nowId < 10) {
          const { data: res } = await this.$http.post("SystemmenusecondAction/addObject", this.addForm)
          if (!res.success) return this.$message.error('添加失败')
          this.$message.success('添加记录成功！')
          this.addDialogVisible = false
          this.getTableList()
        } else if (this.nowId < 100) {
          const { data: res } = await this.$http.post("SystemmenuthirdAction/addObject", this.addForm)
          if (!res.success) return this.$message.error('添加失败')
          this.$message.success('添加记录成功！')
          this.addDialogVisible = false
          this.getTableList()
        } else {
          const { data: res } = await this.$http.post("SystemmenubuttonAction/addObject", this.addForm)
          if (!res.success) return this.$message.error('添加失败')
          this.$message.success('添加记录成功！')
          this.addDialogVisible = false
          this.getTableList()
        }

      })


    },
    // 查看修改记录（当前记录）
    async showEditDialog (id) {
      this.editForm = {}
      if (id < 10) {
        const { data: res } = await this.$http.post("SystemmenuAction/getObjectById", { id })
        if (!res.success) return this.$message.error('获取信息失败')
        this.editForm = res.rows[0]
        this.editForm.rank = this.editForm.rank * 10
        this.editDialogVisible = !this.editDialogVisible
      } else if (id < 100) {
        const { data: res } = await this.$http.post("SystemmenusecondAction/getObjectById", { id })
        if (!res.success) return this.$message.error('获取信息失败')
        this.editForm = res.rows[0]
        this.editForm.rank = this.editForm.rank * 10
        this.editDialogVisible = !this.editDialogVisible
      } else if (id < 1000) {
        const { data: res } = await this.$http.post("SystemmenuthirdAction/getObjectById", { id })
        if (!res.success) return this.$message.error('获取信息失败')
        this.editForm = res.rows[0]
        this.editForm.rank = this.editForm.rank * 10
        this.editDialogVisible = !this.editDialogVisible
      } else {
        const { data: res } = await this.$http.post("SystemmenubuttonAction/getObjectById", { id })
        if (!res.success) return this.$message.error('获取信息失败')
        this.editForm = res.rows[0]
        this.editForm.rank = this.editForm.rank * 10
        this.editDialogVisible = !this.editDialogVisible
      }


    },
    // 确认修改
    editRecordInfo () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        //对rank进行处理，转化为浮点型
        this.editForm.rank = this.editForm.rank / 10
        // 发起修改记录信息的数据请求
        if (this.editForm.id < 10) {
          const { data: res } = await this.$http.post("SystemmenuAction/updateNoNull", this.editForm)
          if (!res.success) return this.$message.error('更新信息失败！')
          this.editDialogVisible = false
          this.getTableList()
          this.$message.success('更新信息成功！')
        } else if (this.editForm.id < 100) {
          const { data: res } = await this.$http.post("SystemmenusecondAction/updateNoNull", this.editForm)
          if (!res.success) return this.$message.error('更新信息失败！')
          this.editDialogVisible = false
          this.getTableList()
          this.$message.success('更新信息成功！')
        } else if (this.editForm.id < 1000) {
          const { data: res } = await this.$http.post("SystemmenuthirdAction/updateNoNull", this.editForm)
          if (!res.success) return this.$message.error('更新信息失败！')
          this.editDialogVisible = false
          this.getTableList()
          this.$message.success('更新信息成功！')
        } else {
          const { data: res } = await this.$http.post("SystemmenubuttonAction/updateNoNull", this.editForm)
          if (!res.success) return this.$message.error('更新信息失败！')
          this.editDialogVisible = false
          this.getTableList()
          this.$message.success('更新信息成功！')
        }


      })
    },
    // 删除（当前记录）
    async deleteRecordById (id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户确认删除，返回值为字符串confirm
      // 如果用户取消删除，返回值未字符串cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      await deleteCurrent(id).then((res) => {
        if (res.meta.status !== 200) {
          return this.$message.error('删除记录失败！')
        }
        this.$message.success('删除记录成功！')
        this.getTableList()
      })

    },
    // 查看详情（当前记录）
    async getDetailInfo (id) {
      await getDetail(id).then((res) => {
        if (res.data.code != 200) {
          return this.$message.error('获取详情信息失败！')
        }
        this.detailForm = res.data.detailInfo
      })
      this.drawerVisible = true

    },
    // 修改switch开关状态（当前记录）
    async switchStateChanged (recordinfo) {
      console.log(recordinfo)
      await modifySwitch(recordinfo.id, recordinfo.state).then((res) => {
        if (res.data.code !== 200) {
          recordinfo.state = !recordinfo.state
          return this.$message.error('更新状态失败!')
        }
        this.$message.success('更新状态成功!')
      })

    },

  }

}


</script>
<style scoped>
.el-table {
  font-size: 13px;
}
.el-pagination {
  text-align: left;
  padding-top: 20px;
}
</style>